<!--
 * @Author: weikang
 * @Description:
 * @Date: 2024-01-21 16:52:27
 * @LastEditTime: 2024-02-26 16:43:26
 * @FilePath: \env-manager-pc\src\views\data_query\powers\components\lineChart.vue
-->
<script setup lang="ts">
import * as Echarts from 'echarts'
import dayjs from 'dayjs'

const props = defineProps({
  tableData: {
    type: Object,
    default: () => ({}),
  },
  markerIDs: {
    type: Array,
    default: () => ([]),
  },
})

let chart: any = null
// const series = ref<any>([])
const currentData = computed(() => {
  return props.tableData[props.markerIDs[0] as string] || []
})
const timeLine = computed(() => {
  return currentData.value.map((item: any) => item.time)
})
const data = computed(() => {
  return currentData.value.map((item: any) => [item.time, item.value])
})
const chartRef = ref<any>()

onMounted(() => {
  chart = Echarts.init(chartRef.value)
  window.addEventListener('resize', () => {
    chart.resize()
  })
})

function getOption() {
  return {
    tooltip: {
      trigger: 'axis',
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      top: 30,
      containLabel: true,
    },
    xAxis: {
      type: 'time',
      boundaryGap: false,
      min: timeLine.value[0],
      axisLabel: {
        formatter(value: any) {
          // 返回自定义的时间格式
          return dayjs(value).format('HH:mm')
        },
      },
    },
    yAxis: {
      type: 'value',
      name: 'kW',
      scale: true,
      nameTextStyle: {
        padding: [0, 0, 0, 60],
      },
    },
    series: [{
      name: '功率',
      type: 'line',
      data: data.value,
      smooth: true,
      symbol: 'none',
      lineStyle: {
        width: 1,
      },
    }],
  }
}

onMounted(() => {
  chart = Echarts.init(chartRef.value)
  calcHeight()
  window.addEventListener('resize', () => {
    calcHeight()
  })
})

function calcHeight() {
  nextTick(() => {
    const footHeight = 40
    const top = chartRef.value.getBoundingClientRect().top
    const windowHeight = window.innerHeight
    const companyHeight = 50
    const height = windowHeight - top - footHeight - companyHeight
    chartRef.value.style.height = `${height}px`
    chart.resize()
  })
}

function refresh() {
  chart.setOption(getOption())
}

defineExpose({
  refresh,
})
</script>

<template>
  <div ref="chartRef" style="width: 100%; height: 100%;" />
</template>
